// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const userId = wxContext.OPENID
  
  try {
    const { date } = event
    
    if (!date) {
      return {
        status: 'error',
        message: '参数错误：缺少日期'
      }
    }
    
    const targetDate = new Date(date)
    
    // 获取所有周期记录
    const cyclesRes = await db.collection('cycles')
      .where({
        user_id: userId
      })
      .orderBy('start_date', 'desc')
      .limit(10)
      .get()
    
    const cycles = cyclesRes.data || []
    
    // 默认返回数据
    let cycleInfo = {
      inPeriod: false,
      periodDay: 0,
      isFertile: false,
      isOvulation: false,
      cycleDay: 0
    }
    
    if (cycles.length === 0) {
      return {
        status: 'success',
        data: cycleInfo
      }
    }
    
    // 查找包含目标日期的周期
    let currentCycle = null
    
    for (const cycle of cycles) {
      const startDate = new Date(cycle.start_date)
      const endDate = cycle.end_date ? new Date(cycle.end_date) : new Date()
      
      // 如果目标日期在周期范围内
      if (targetDate >= startDate && targetDate <= endDate) {
        currentCycle = cycle
        break
      }
    }
    
    // 如果找到包含目标日期的周期
    if (currentCycle) {
      const startDate = new Date(currentCycle.start_date)
      
      // 计算是周期的第几天
      const cycleDay = Math.floor((targetDate - startDate) / (24 * 60 * 60 * 1000)) + 1
      cycleInfo.cycleDay = cycleDay
      
      // 获取该周期的经期记录
      const periodRecords = await db.collection('daily_records')
        .where({
          user_id: userId,
          date: _.gte(startDate),
          flow_level: _.gte(0)
        })
        .orderBy('date', 'asc')
        .get()
      
      // 计算经期天数
      const periodDays = periodRecords.data.length
      
      // 判断是否在经期内
      if (periodRecords.data.some(record => {
        const recordDate = new Date(record.date)
        return recordDate.getFullYear() === targetDate.getFullYear() &&
               recordDate.getMonth() === targetDate.getMonth() &&
               recordDate.getDate() === targetDate.getDate()
      })) {
        cycleInfo.inPeriod = true
        
        // 计算是经期第几天
        for (let i = 0; i < periodRecords.data.length; i++) {
          const recordDate = new Date(periodRecords.data[i].date)
          if (recordDate.getFullYear() === targetDate.getFullYear() &&
              recordDate.getMonth() === targetDate.getMonth() &&
              recordDate.getDate() === targetDate.getDate()) {
            cycleInfo.periodDay = i + 1
            break
          }
        }
      }
      
      // 计算平均周期长度
      let avgCycleLength = 28 // 默认周期长度
      
      if (cycles.length >= 2) {
        let totalLength = 0
        let count = 0
        
        for (let i = 0; i < cycles.length - 1; i++) {
          if (cycles[i].end_date && cycles[i + 1].start_date) {
            const current = new Date(cycles[i].start_date)
            const next = new Date(cycles[i + 1].start_date)
            const length = Math.floor((current - next) / (24 * 60 * 60 * 1000))
            
            if (length > 0 && length < 60) { // 过滤异常值
              totalLength += length
              count++
            }
          }
        }
        
        if (count > 0) {
          avgCycleLength = Math.round(totalLength / count)
        }
      }
      
      // 计算排卵日（通常是下次经期前14天）
      const ovulationDay = avgCycleLength - 14
      
      // 判断是否是排卵日
      if (cycleDay === ovulationDay) {
        cycleInfo.isOvulation = true
      }
      
      // 判断是否在排卵期（排卵日前后5天）
      if (cycleDay >= ovulationDay - 3 && cycleDay <= ovulationDay + 2) {
        cycleInfo.isFertile = true
      }
    }
    
    return {
      status: 'success',
      data: cycleInfo
    }
  } catch (err) {
    return {
      status: 'error',
      message: err.message,
      error: err
    }
  }
} 